/**
 * Created by Johnny on 2017/2/5.
 */
function UserProfile() {

    var pageid = 'layout_user_profile';
    var profile = this;
    var url_upload_avatar = apiloc + '/v1/user/uploadAvatar';

    $.validator.addMethod('mobile', function( value, element ) {
        return this.optional( element ) || /^1[34578]\d{9}$/.test( value );
    }, pfuser_i18n.msg_validmobile);

    $.validator.addMethod('phone', function( value, element ) {
        return this.optional( element ) || /^((0\d{2,3})-)(\d{7,8})(-(\d{3,}))?$/.test( value );
    }, pfuser_i18n.msg_validphone);

    $.validator.addMethod('password1', function( value, element ) {
        return this.optional( element ) || /^(\w)[a-zA-Z0-9]|[_]$/.test( value );
    }, pfuser_i18n.msg_validpwd);

    var resetChangeBasic = function() {
        $('#layout_user_profile .form-user-basic .form-control').each(function (idx, obj) {
            $(obj).val(profile.user[$(obj).attr('name')] || '');
        });
    }

    var resetChangeExt = function() {
        $('#layout_user_profile .form-user-ext .form-control').each(function (idx, obj) {
            $(obj).val(profile.user[$(obj).attr('name')] || '');
        });
    }

    var handleChangeBasic = function() {//change basic info

        //get info for basic and ext panel
        doGetAsyncJson(apiloc + '/v1/user/current?withExt=true', function(ret) {
            profile.user = ret;
            resetChangeBasic();
            resetChangeExt();

            //必须数据加载之后，否则取不到profile.user.userId
            $('#layout_user_profile .form-user-basic').validate({
                errorElement: 'span',
                errorClass: 'help-block',
                focusInvalid: false,
                onkeyup: false,
                rules: {
                    realName: {
                        required: true,
                        maxlength: 20,
                        minlength: 2
                    },
                    email : {
                        required: true,
                        email: true,
                        remote : {
                            url: "/bpmp-engine/openapi/v1/user/checkAttr",
                            data : {"userId": profile.user.userId},
                            type: "GET"
                        },
                        maxlength: 40
                    },
                    mobile : {
                        required: true,
                        mobile: true,
                        remote : {
                            url: "/bpmp-engine/openapi/v1/user/checkAttr",
                            data : {"userId": profile.user.userId},
                            type: "GET"
                        }
                    },
                    gender : {
                        required: true
                    }
                },

                messages: {
                    email : {
                        remote : pfuser_i18n.msg_usedemail
                    },
                    mobile : {
                        remote : pfuser_i18n.msg_usedmobile
                    }
                },

                highlight: function (element) {
                    $(element).closest('.form-group').addClass('has-error');
                },

                success: function (label) {
                    label.closest('.form-group').removeClass('has-error');
                    label.remove();
                },

                errorPlacement: function (error, element) {
                    error.insertAfter(element.closest('.form-control'));
                },

            });

            handleAvatar();

        });

        function submitChangeBasic() {
            if ($("#layout_user_profile .form-user-basic").validate().form()) {
                $("#layout_user_profile .form-user-basic").ajaxSubmit({
                    type: 'post',
                    url: '/bpmp-engine/api/v1/user/update',
                    data: {},
                    success: function (data) {
                        if (data && data.result) {
                            profile.user.realName = $('#layout_user_profile .form-user-basic [name="realName"]').val();
                            profile.user.email = $('#layout_user_profile .form-user-basic [name="email"]').val();
                            profile.user.mobile = $('#layout_user_profile .form-user-basic [name="mobile"]').val();
                            profile.user.gender = $('#layout_user_profile .form-user-basic [name="gender"]').val();
                            //modalAlert(null, '操作成功', '个人信息修改成功。', null, '关闭');
                            msg(pfuser_i18n.msg_succupdate);
                        } else {
                            onErrorChangeBasic(data.errorCode);
                        }
                    },
                    error : onErrorChangeBasic
                });
            }
        }

        function onErrorChangeBasic (errorCode){
            //modalAlert('error', i18nindex.fail, i18nindex.msg_commiterr, null, '关闭');
            msgErr(i18nindex.msg_commiterr);
        }

        $('#layout_user_profile .form-user-basic .btn-save').click(function() {
            submitChangeBasic();
        });

        $('#layout_user_profile .form-user-basic .btn-reset').click(function() {
            resetChangeBasic();
        });
    }

    var handleChangeExt = function() {//change extension info

        $('#layout_user_profile .form-user-ext [name="birthday"]').datepicker({
            format: 'yyyy-mm-dd',
            autoclose: true,
            endDate: '0d',
            language: lang_dp
        });

        $('#layout_user_profile .form-user-ext').validate({
            errorElement: 'span',
            errorClass: 'help-block',
            focusInvalid: false,
            rules: {
                phone: {
                    required: true,
                    phone: true
                },
                birthday : {
                    //required: true
                },
                address : {
                    maxlength: 40
                }
            },

            highlight: function (element) {
                $(element).closest('.form-group').addClass('has-error');
            },

            success: function (label) {
                label.closest('.form-group').removeClass('has-error');
                label.remove();
            },

            errorPlacement: function (error, element) {
                error.insertAfter(element.closest('.form-control'));
            },

        });

        function submitChangeExt() {
            if ($("#layout_user_profile .form-user-ext").validate().form()) {
                $("#layout_user_profile .form-user-ext").ajaxSubmit({
                    type: 'post',
                    url: '/bpmp-engine/api/v1/user/updateExt',
                    data: {},
                    success: function (data) {
                        if (data && data.result) {
                            profile.user.phone = $('#layout_user_profile .form-user-ext [name="phone"]').val();
                            profile.user.birthday = $('#layout_user_profile .form-user-ext [name="birthday"]').val();
                            profile.user.address = $('#layout_user_profile .form-user-ext [name="address"]').val();
                            //modalAlert(null, '操作成功', '个人信息修改成功。', null, '关闭');
                            msg(pfuser_i18n.msg_succupdate);
                        } else {
                            onErrorChangeExt(data.errorCode);
                        }
                    },
                    error : onErrorChangeExt
                });
            }
        }

        function onErrorChangeExt(errorCode){
            //modalAlert('error', i18nindex.fail, i18nindex.msg_commiterr, null, '关闭');
            msgErr(i18nindex.msg_commiterr);
        }

        $('#layout_user_profile .form-user-ext .btn-save').click(function() {
            submitChangeExt();
        });

        $('#layout_user_profile .form-user-ext .btn-reset').click(function() {
            resetChangeExt();
        });
    }

    var handleChangePwd = function() {

        $('#layout_user_profile .form-user-pwd').validate({
            errorElement: 'span',
            errorClass: 'help-block',
            focusInvalid: false,
            rules: {
                oldPwd: {
                    required: true,
                    /*remote : {
                        url: "/bpmp-engine/openapi/v1/user/checkAttr",
                        data : {"reverse" : "true"},
                        type: "GET"
                    },*/
                    maxlength: 20
                },
                newPwd : {
                    required: true,
                    password1: true,
                    maxlength: 20
                },
                rNewPwd : {
                    required: true,
                    password1: true,
                    maxlength: 20,
                    equalTo: "#new_password"
                }
            },

            highlight: function (element) {
                $(element).closest('.form-group').addClass('has-error');
            },

            success: function (label) {
                label.closest('.form-group').removeClass('has-error');
                label.remove();
            },

            errorPlacement: function (error, element) {
                error.insertAfter(element.closest('.form-control'));
            },

        });

        function submitChangePwd() {
            if ($("#layout_user_profile .form-user-pwd").validate().form()) {
                $("#layout_user_profile .form-user-pwd").ajaxSubmit({
                    type: 'post',
                    url: '/bpmp-engine/api/v1/user/changePwd',
                    data: {},
                    success: function (data) {
                        if (data && data.result) {
                            resetPwds();
                            modalAlert(null, i18nindex.succ, pfuser_i18n.msg_pwdchanged, i18nindex.y, i18nindex.n, function(){
                                window.location.href = '/logout';
                            });
                        } else {
                            onErrorChangePwd(data.errorCode);
                        }
                    },
                    error : onErrorChangePwd
                });
            }
        }

        function resetPwds() {
            $('#layout_user_profile .form-user-pwd [name="oldPwd"]').val('');
            $('#layout_user_profile .form-user-pwd [name="newPwd"]').val('');
            $('#layout_user_profile .form-user-pwd [name="rNewPwd"]').val('');
        }

        function onErrorChangePwd(errorCode) {
            if (errorCode=='WRONG_OLD_PWD') {
                modalAlert('warning', i18nindex.fail, pfuser_i18n.msg_wrongcurpwd, null, i18nindex.close);
            } else {
                //modalAlert('error', i18nindex.fail, i18nindex.msg_commiterr, null, i18nindex.close);
                msgErr(i18nindex.msg_commiterr);
            }
        }

        $('#layout_user_profile .form-user-pwd .btn-reset-pwd').click(function () {
            submitChangePwd();
        });

        resetPwds();
    }

    var handleChangeSetting = function() {//change settings

    }

    var handleAvatar = function() {
        if (window.avatarEnabled) {
            refreshAvatar();
            $.getScript(resloc+"/static/jslib/bootstrap/global/plugins/jquery-jcrop/jquery.Jcrop.min.js?"+productionVersion);
            $('#'+pageid+' .avatar-area').show().find('.btn-setavatar').click(showSetAvatarModal);
        }
    }

    var refreshAvatar = function () {
        var avatarUrl = window.avatarOssUrlPrefix + encodeURIComponent(base64encode(profile.user.loginName)) + '.'+avatarExt+'?'+new Date().getTime();
        $('#'+pageid+' .avatar-area img.current-avatar').attr('src', avatarUrl);
        $('.top-menu .header-avatar').attr('src', avatarUrl);
    }
    
    var showSetAvatarModal = function () {
        var modal = bootbox.dialog({
            title : '',
            message : '<div>' +
                            '<div class="row">' +
                                '<div class="col-xs-12" style="text-align:left">' +
                                    '<div class="file-container" style="display:inline-block;position:relative;overflow: hidden;vertical-align:middle">' +
                                        '<button class="btn btn-sm btn-circle btn-success fileinput-button" type="button" style="margin-left:40px;">选择图片</button>' +
                                        '<input type="file" class="input-file" accept="image/x-png,image/gif,image/jpeg,image/bmp" style="position:absolute;top:0;left:0;font-size:30px; opacity:0;cursor:pointer;width:100px;margin-left:40px;">' +
                                    '</div>' +
                                    '<span style="margin-left:10px;color:gray">'+pfuser_i18n.title_crop+'</span>'+
                                '</div>' +
                            '</div>' +
                            '<div class="row">' +
                                '<div class="col-xs-12" style="min-height:500px;margin-top:10px;text-align: center">' +
                                    '<div style="width:500px; min-height:500px; border: 1px solid #ccdee6; margin-left:35px;">'+
                                        '<img class="img-crop" width="500">'+
                                    '</div>'+
                                '</div>' +
                            '</div>'+
                      '</div>',
            onEscape : true,
            buttons : {
                ok: {
                    label: i18nindex.save,
                    className: 'blue',
                    callback : function() {
                        //console.log(modal.cropdata);
                        var formData = new FormData();
                        if (!modal.inputfile[0].files || !modal.inputfile[0].files[0]) {
                            msgWarning(i18nindex.msg_plsselavatarimg);return false;
                        }
                        var name = modal.inputfile[0].files[0].name;
                        var ext = name.substr(name.lastIndexOf('.')+1);
                        var file = modal.inputfile[0].files[0];
                        formData.append("file", file);
                        formData.append("ext", ext);
                        formData.append("cropdata", JSON.stringify(modal.cropdata));
                        $.ajax({
                            url: url_upload_avatar,
                            type: 'POST',
                            cache: false,
                            data: formData,
                            processData: false,
                            contentType: false
                        }).done(function(res) {
                            if (res && res.result) {
                                msg(i18nindex.succ);
                                refreshAvatar();
                            } else {
                                msgErr(i18nindex.msg_commiterr);
                            }
                            modal.modal('hide');
                            Metronic.unblockUI(); //workaround for ajax bug
                        }).fail(function(err) {
                            msgErr(i18nindex.msg_commiterr);
                            modal.modal('hide');
                            Metronic.unblockUI(); //workaround for ajax bug
                        });
                        return false;
                    }
                },
                cancel: {
                    label: i18nindex.cancel,
                    className: 'btn-default',
                    callback : function() {
                        return true;
                    }
                }
            }
        }).on('shown.bs.modal', function() {
            modal.inputfile = modal.find('.input-file');
            modal.inputfile.change(inputChange);
            var jcrop_api;

            function inputChange(e) {
                var file = e.target;
                if (!file.files || !file.files[0]) return;
                //check size
                if (file.files[0].size>409600) {
                    msgWarning(pfuser_i18n.msg_imgtoolarge);return;
                } else if (file.files[0].size==0) {
                    msgWarning(pfuser_i18n.msg_imginvalidsize);return;
                }

                jcrop_api && jcrop_api.destroy();
                var imgCrop = modal.find('img.img-crop');
                imgCrop.attr('src', '');
                var reader = new FileReader();
                reader.onload = function (evt) {
                    imgCrop[0].onload = function () {
                        //mark cropping
                        imgCrop.Jcrop({
                            bgColor: 'gray',
                            aspectRatio: 1/1,
                            allowSelect: false,
                            onChange: function (c) {
                                modal.cropdata = c;
                                //record orgin size
                                modal.cropdata.naturalWidth = imgCrop[0].naturalWidth; //h5
                                modal.cropdata.naturalHeight = imgCrop[0].naturalHeight;
                                modal.cropdata.zoomScale = Number((imgCrop[0].naturalWidth / imgCrop[0].width).toFixed(2));
                                //console.log(modal.cropdata);
                            }
                        },function(){
                            jcrop_api = this;
                            jcrop_api.animateTo([0,0,500,500]);
                        });
                    }
                    imgCrop.attr('src', evt.target.result);
                }
                reader.readAsDataURL(file.files[0]);
            }
        });
    }

    return {
        init: function () {
            handleChangeBasic();
            handleChangeExt();
            handleChangePwd();
            handleChangeSetting();
        }
    };

}